using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;

namespace GoodStuff
{
    public class GoodNumericUpDown : GoodControlContainerBase, IGoodControl
    {

        public GoodNumericUpDown()
        {
            Trace.WriteLine("GoodNumericUpDown constructor called");
            _control = new NumericUpDown();
            _charactersWide = 4;
        }

        override protected void OnVariableChanged(object sender, EventArgs args)
        {
            if (!_updating)
            {
                _updating = true;
                Decimal d = (_variable as IGoodNumericVariable).ToDecimal(null);
                if (d != (_control as NumericUpDown).Value)
                    (_control as NumericUpDown).Value = d;
                _updating = false;
            }
        }

        public override void Initialize()
        {
            Trace.WriteLine("Initializing GoodNumericUpDown " + _variable.Name);
            if (!(_variable is IGoodNumericVariable))
                throw (new Exception("GoodNumericUpDown must refer to a variable that implements IGoodNumericVariable"));

            NumericUpDown control = (_control as NumericUpDown);

            control.BeginInit();
            control.TextAlign = HorizontalAlignment.Right;
            _control.Anchor = AnchorStyles.None;
            _control.AutoSize = false;


            // BEGIN: cheezy code block
            Graphics g = _control.CreateGraphics();
            int d = (int)Math.Pow(10, _charactersWide) - 1;
            SizeF t = g.MeasureString(d.ToString(), _control.Font);
            _control.Size = new Size((int)t.Width + 30, _control.Height);
            control.Maximum = Decimal.MaxValue;
            control.Minimum = Decimal.MinValue;
            control.Value = (_variable as IGoodNumericVariable).ToDecimal(null);
            // END: cheezy code ends here

            control.ValueChanged += OnValueChanged;
            control.EndInit();

            base.Initialize();
        }

        public void OnValueChanged(object sender, EventArgs e)
        {
            if (!_updating)
            {
                _updating = true;
                Trace.WriteLine("GoodNumericUpDown " + _variable.Name + " changed in UI");
                if (_variable != null)
                {
                    (_variable as IGoodNumericVariable).Set((_control as NumericUpDown).Value);
                }
                _updating = false;
            }
        }
    }
}
